<template>
  <div>
    <search-table
      :url="url"
      ref="searchtable"
      :columns="columns"
      :form="form"
      :xLength="1500"
      :defaultSelectedRowKeys="chosenIds"
      :rowSelectionSelect="rowSelectionSelect"
      :rowSelectionChange="rowSelectionChange"
      :rowSelectInvert="rowSelectInvert"
      @initChosenIds="initChosenIds"
    >
      <template slot="searchForm">
        <a-form layout="inline" :form="form">
          <a-form-item label="创建所属">
            <a-select
              style="width: 200px"
              :options="
                userInfo.isHeadMainStore == 1 ? createFrom2 : createFrom1
              "
              v-decorator="['shopType', { initialValue: 1 }]"
              placeholder="请选择创建所属"
            />
          </a-form-item>
          <a-form-item label="活动名称">
            <a-input
              style="width: 200px"
              v-decorator="['name']"
              placeholder="请输入活动名称"
              autocomplete="off"
            >
            </a-input>
          </a-form-item>

          <a-form-item label="活动创建时间">
            <fast-range-picker
              allowClear
              v-decorator="['startCreateDate-endCreateDate']"
            >
            </fast-range-picker>
          </a-form-item>

          <a-form-item label="活动状态">
            <a-select
              style="width: 200px"
              :options="activityStatus"
              v-decorator="['status', { initialValue: '' }]"
              placeholder="请选择活动状态"
            />
          </a-form-item>

          <a-form-item label="创建店铺">
            <a-input
              style="width: 200px"
              v-decorator="['shopName']"
              placeholder="请输入店铺名称"
              autocomplete="off"
            >
            </a-input>
          </a-form-item>

          <a-form-item label="创建人">
            <a-input
              style="width: 200px"
              v-decorator="['username']"
              placeholder="请输入创建人"
              autocomplete="off"
            >
            </a-input>
          </a-form-item>
        </a-form>
      </template>
      <template slot="oprationRow" v-if="userInfo.userIdType == 1">
        <!-- <a-button type="primary" icon="plus" @click="addNewActivity()"
          >创建活动</a-button
        > -->
        <a-button @click="deleteMoreRows">删除</a-button>
      </template>

      <template slot="tableOperation" slot-scope="{ record }">
        <a-space v-if="userInfo.userIdType == 1">
          <permission authority="sale:card:info">
            <a
              href="javascript:;"
              class="text-primary pointer"
              @click="preview(record.id)"
              >查看活动</a
            >
          </permission>
          <permission authority="order:page">
            <permission authority="sale:card:statistics">
              <a
                href="javascript:;"
                class="text-primary pointer"
                @click="orderInfo(record)"
                >查看订单</a
              >
            </permission>
          </permission>
          <a
            href="javascript:;"
            class="text-primary pointer"
            @click="updateProduct(record.id)"
            v-if="userInfo.userId == record.createBy && record.status == 1"
            >编辑活动</a
          >
          <a
            href="javascript:;"
            class="text-notallowed pointer"
            v-if="userInfo.userId == record.createBy && record.status != 1"
            >编辑活动</a
          >
          <a
            href="javascript:;"
            class="text-primary pointer"
            @click="pauseRows(record.id)"
            v-if="userInfo.userId == record.createBy && record.status == 2"
            >暂停</a
          >
          <a
            href="javascript:;"
            class="text-primary pointer"
            @click="continueActive(record.id)"
            v-if="userInfo.userId == record.createBy && record.status == 3"
            >继续活动</a
          >
          <a
            href="javascript:;"
            class="text-notallowed pointer"
            v-if="
              userInfo.userId == record.createBy &&
              record.status != 2 &&
              record.status != 3
            "
            >暂停</a
          >
          <a
            href="javascript:;"
            class="text-primary pointer"
            @click="endingRows(record.id)"
            v-if="userInfo.userId == record.createBy && record.status != 4"
            >提前结束</a
          >
          <a
            href="javascript:;"
            class="text-notallowed pointer"
            v-if="userInfo.userId == record.createBy && record.status == 4"
            >提前结束</a
          >
          <a
            href="javascript:;"
            class="text-primary pointer"
            @click="deleteRows([{ id: record.id, userId: record.createBy }])"
            v-if="userInfo.userId == record.createBy && record.status == 1"
            >删除</a
          >
          <a
            href="javascript:;"
            class="text-notallowed pointer"
            v-if="userInfo.userId == record.createBy && record.status != 1"
            >删除</a
          >
          <!-- <a
            href="javascript:;"
            class="text-primary pointer"
            v-if="userInfo.userId == record.createBy"
            >门店订单</a
          > -->
        </a-space>
        <a-space v-else>
          <permission authority="sale:card:info">
            <a
              href="javascript:;"
              class="text-primary pointer"
              @click="preview(record.id)"
              >查看活动</a
            >
          </permission>
          <permission authority="order:page">
            <permission authority="sale:card:statistics">
              <a
                href="javascript:;"
                class="text-primary pointer"
                @click="orderInfo(record)"
                >查看订单</a
              >
            </permission>
          </permission>
        </a-space>
      </template>
    </search-table>
    <addActivity
      @cancel="closeInfoModal"
      :visible="visible"
      @freshTable="initTable"
      :activeId="activeId"
      :opration="opration"
    ></addActivity>
    <preview
      :previewVisible="previewVisible"
      @cancel="closePreviewModal"
      :previewId="previewId"
    ></preview>
  </div>
</template>
<script>
import addActivity from "./components/addActivity.vue";
import preview from "./components/preview.vue";
import { mapState } from "vuex";
export default {
  name: "sellCard",
  components: {
    addActivity,
    preview,
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.userInfo,
    }),
  },
  data() {
    return {
      form: this.$form.createForm(this, { name: "table_search" }),
      url: "/sale/card/page",
      columns: [
        {
          title: "活动名称",
          dataIndex: "name",
          key: "name",
          align: "center",
        },
        {
          title: "活动封面",
          dataIndex: "coverImages",
          key: "coverImages",
          align: "center",
          customRender: (text, row) => {
            text = text.split(",")[0];
            return <table-img src={text} />;
          },
        },
        {
          title: "所属店铺",
          dataIndex: "shopName",
          key: "shopName",
          align: "center",
        },
        {
          title: "所属机构",
          dataIndex: "orgName",
          key: "orgName",
          align: "center",
        },
        {
          title: "活动状态",
          dataIndex: "status",
          key: "status",
          align: "center",
          customRender: (text, row) => {
            if (text == 1) {
              text = "未发布";
            } else if (text == 2) {
              text = "进行中";
            } else if (text == 3) {
              text = "已暂停";
            } else if (text == 4) {
              text = "已结束";
            }
            return text;
          },
        },
        {
          title: "创建时间",
          dataIndex: "createDate",
          key: "createDate",
          align: "center",
        },
        {
          title: "创建人",
          dataIndex: "username",
          key: "username",
          align: "center",
        },
        {
          title: "联系电话",
          dataIndex: "phone",
          key: "phone",
          align: "center",
        },
        {
          title: "操作",
          dataIndex: "operation",
          fixed: "right",
          scopedSlots: { customRender: "operation" },
        },
      ],
      //非总部总店登录
      createFrom1: [
        { label: "本店创建", value: 1 },
        { label: "总部创建", value: 3 },
      ],
      //总部总店登录
      createFrom2: [
        { label: "本店创建", value: 1 },
        { label: "其它店创建", value: 2 },
      ],
      activityStatus: [
        { label: "全部", value: "" },
        { label: "进行中", value: 2 },
        { label: "已结束", value: 4 },
        { label: "已暂停", value: 3 },
        { label: "未发布", value: 1 },
      ],
      visible: false,
      previewVisible: false,
      opration: "add",
      activeId: "", //活动id
      previewId: "", //预览活动Id
      chosenIds: [], // 不同分页下被选中的表格行id集合
      allSelectedRows: [], // 不同分页下被选中的表格行
    };
  },
  methods: {
    //清空已选中
    initChosenIds() {
      this.chosenIds = [];
      this.allSelectedRows = [];
    },
    // 表格单行选择
    rowSelectionSelect(record, selected) {
      if (!selected) {
        this.allSelectedRows.splice(
          this.allSelectedRows.findIndex((item) => item.id == record.id),
          1
        );
        this.chosenIds.splice(
          this.chosenIds.findIndex((item) => item == record.id),
          1
        );
      }
    },
    // 表格任意行发生选择或取消选择时回调
    rowSelectionChange(selectedRowKeys, selectedRows) {
      let _this = this;
      if (selectedRows.length > 0) {
        selectedRows.forEach((item) => {
          if (!_this.chosenIds.includes(item.id)) {
            _this.chosenIds.push(item.id);
            _this.allSelectedRows.push(item);
          }
        });
        selectedRowKeys = this.chosenIds;
        this.$refs.searchtable.selectedRowKeys = this.chosenIds;
      } else {
      }
    },
    rowSelectInvert(selected, selectedRows, changeRows) {
      if (!selected) {
        let ids = [];
        changeRows.forEach((item) => {
          ids.push(item.id);
        });
        this.chosenIds = this.chosenIds.filter(function (val) {
          return ids.indexOf(val) === -1;
        });
        let arr = [];
        this.allSelectedRows.forEach((item) => {
          if (this.chosenIds.includes(item.id)) {
            arr.push(item);
          }
        });
        this.allSelectedRows = arr;
      }
    },
    //新增活动
    addNewActivity() {
      this.opration = "add";
      this.visible = true;
    },
    //编辑活动
    updateProduct(id) {
      this.opration = "update";
      this.visible = true;
      this.activeId = id;
    },
    //多删活动
    deleteMoreRows() {
      if (this.allSelectedRows.length == 0) {
        this.$message.warn("请先选择一项后再进行操作");
      } else {
        let arr = [];
        this.allSelectedRows.forEach((item) => {
          if (item.createBy != this.userInfo.userId || item.status != 1) {
            arr.push(item);
          }
        });
        if (arr.length > 0) {
          this.$message.error("非本店本人创建和已经进行过的活动不能删除");
        } else {
          let array = [];
          this.allSelectedRows.forEach((item) => {
            array.push({
              id: item.id,
              userId: item.createBy,
            });
          });
          this.deleteRows(array);
        }
      }
    },
    //删除活动
    deleteRows(ids) {
      if (!ids || ids.length === 0)
        return this.$message.warn("请先选择一项后再进行操作");
      this.$confirm({
        title: "确定删除活动？",
        content: "活动删除后无法查看活动订单",
        okText: "确认删除",
        cancelText: "取消",
        onOk: () => {
          this.$post("/sale/card/delete", ids).then((res) => {
            if (res && res.returnCode == 1000) {
              this.$message.success("删除成功");
              this.$refs.searchtable.refreshTable();
              this.initChosenIds();
            }
          });
        },
      });
    },
    endingRows(ids) {
      this.$confirm({
        title: "确定提前结束活动？",
        content: "结束后无法恢复活动",
        okText: "确认结束",
        cancelText: "取消",
        onOk: () => {
          let params = {};
          params.status = 4;
          params.id = ids;
          this.$post("/sale/card/update", params).then((res) => {
            if (res && res.returnCode == 1000) {
              this.$message.success("操作成功");
              this.$refs.searchtable.refreshTable();
            }
          });
        },
      });
    },
    pauseRows(ids) {
      this.$confirm({
        title: "确定暂停活动？",
        content: "暂停后客户无法参加",
        okText: "确认暂停",
        cancelText: "取消",
        onOk: () => {
          let params = {};
          params.status = 3;
          params.id = ids;
          this.$post("/sale/card/update", params).then((res) => {
            if (res && res.returnCode == 1000) {
              this.$message.success("操作成功");
              this.$refs.searchtable.refreshTable();
            }
          });
        },
      });
    },
    continueActive(ids) {
      this.$confirm({
        title: "确定继续活动？",
        // content: "暂停后客户无法参加",
        okText: "确认继续",
        cancelText: "取消",
        onOk: () => {
          let params = {};
          params.status = 2;
          params.id = ids;
          this.$post("/sale/card/update", params).then((res) => {
            if (res && res.returnCode == 1000) {
              this.$message.success("操作成功");
              this.$refs.searchtable.refreshTable();
            }
          });
        },
      });
    },
    orderInfo(record) {
      this.$router.push({
        name: "MarketingSellCardOrderList",
        query: {
          order: record.id,
        },
      });
    },

    addLable() {},
    upadteLable(id, record) {},

    initTable() {
      this.$refs.searchtable.refreshTable();
    },

    closeInfoModal() {
      this.visible = false;
    },
    preview(id) {
      this.previewVisible = true;
      this.previewId = id;
    },
    closePreviewModal() {
      this.previewVisible = false;
    },
  },
  beforeRouteEnter(to, from, next) {
    // console.log(from.path)
    if (from.path == "/marketing/sellCard/orderList") {
      to.meta.isBack = true;
    } else {
      to.meta.isBack = false;
    }
    to.meta.keepAlive = true;
    next();
  },
  activated() {
    if (!this.$route.meta.isBack) {
      // this.clearFilter(); /*清空查询条件*/
      let oRest = document.querySelector(".resetBtn");
      oRest.click();
    }
  },
};
</script>
<style scoped lang="less">
.platform {
  margin-right: 5px;
}
.text-notallowed {
  color: #b0b0b0;
  cursor: not-allowed;
}
</style>